import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../http/http_agent.dart';
import '../model/contract_list_model.dart';
import '../model/user_contract_model.dart';
import '../service/home_service.dart';
import 'package:flutter/services.dart';

class HomeController extends GetxController with WidgetsBindingObserver {
  final HomeService _homeService = HomeService();

  // 首页数据
  final RxMap<String, dynamic> homeData = <String, dynamic>{}.obs;
  final RxBool isLoadingHomeData = false.obs;

  // 合约列表
  final Rx<ContractListResponse?> contractListData =
      Rx<ContractListResponse?>(null);
  final RxBool isLoadingContracts = false.obs;

  // 我的合约列表
  final Rx<UserContractResponse?> userContractData =
      Rx<UserContractResponse?>(null);
  final RxBool isLoadingUserContracts = false.obs;

  // 轮询相关
  Timer? _pollingTimer;
  final RxBool isPollingEnabled = true.obs;
  final int pollingInterval = 300000; // 5分钟轮询一次
  DateTime _lastDataChangeTime = DateTime.now();
  String _lastDataHash = '';
  int _unchangedDataCount = 0; // 连续无数据变化的次数

  // 便捷访问器 - 优先从homeData获取，fallback到userContractData
  String get btcBalance =>
      homeData.value['btc_num']?.toString() ??
      userContractData.value?.btcNum ??
      '0.000000000000000000';

       // 便捷访问器 - 优先从homeData获取，fallback到userContractData
  String get invitBalance =>
      homeData.value['invite_btc']?.toString() ??
      userContractData.value?.btcInviteNum ??
      '0.000000000000000000';

  String get btcPrice =>
      homeData.value['btc_price']?.toString() ??
      userContractData.value?.btcPrice ??
      '0';
  double get btcTotalValue =>
      (homeData.value['btc_total_value'] as num?)?.toDouble() ??
      userContractData.value?.btcTotalValue ??
      0.0;
  double get btcTotalPower =>
      (homeData.value['power'] as num?)?.toDouble() ??
      userContractData.value?.power ??
      0.0;

  double get freePowerTime =>
      (homeData.value['duration'] as num?)?.toDouble() ?? 0.0;

  List<UserContract> get userContracts =>
      userContractData.value?.contractList ?? [];
  // LineChart? get chartData => userContractData.value?.lineChart;
  int get runningContractsCount =>
      userContractData.value?.runningContractsCount ?? 0;
  // double get totalComputingPower => userContractData.value?.totalComputingPower ?? 0.0;
  bool get hasBtcInfo => userContractData.value?.hasBtcInfo ?? false;
  // bool get hasChartData => userContractData.value?.hasChartData ?? false;
  bool get hasContracts => userContractData.value?.hasContracts ?? false;

  // 总体加载状态
  final RxBool isRefreshing = false.obs;

  @override
  void onInit() {
    super.onInit();
    // 注册应用生命周期监听
    WidgetsBinding.instance.addObserver(this);
    // 启动轮询
    _startPolling();
  }

  @override
  void onClose() {
    // 移除应用生命周期监听
    WidgetsBinding.instance.removeObserver(this);
    // 停止轮询
    _stopPolling();
    super.onClose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // 监听应用生命周期状态变化
    switch (state) {
      case AppLifecycleState.resumed:
        // 应用恢复到前台，重新启动轮询
        if (!isPollingEnabled.value) {
          print('应用恢复前台，重新启动轮询');
          togglePolling(true);
        }
        break;
      case AppLifecycleState.paused:
      case AppLifecycleState.inactive:
      case AppLifecycleState.detached:
        // 应用进入后台或不活跃状态，暂停轮询
        if (isPollingEnabled.value) {
          print('应用进入后台，暂停轮询');
          togglePolling(false);
        }
        break;
      default:
        break;
    }
  }

  /// 加载初始数据
  Future<void> loadInitialData() async {
    await Future.wait([
      getHomeData(), // 启用首页数据加载
    ]);
  }

  /// 获取首页数据
  Future<void> getHomeData() async {
    try {
      isLoadingHomeData.value = true;
      print('开始获取首页数据...');
      final response = await _homeService.getHomeData();

      if (response.isSuccess && response.data != null) {
        homeData.value = response.data!;
        // 更新最后一次数据变更时间和数据哈希值
        _lastDataChangeTime = DateTime.now();
        _lastDataHash = response.data.toString().hashCode.toString();
        print('首页数据加载成功: ${response.data}');
        print('BTC余额: ${btcBalance}');
        print('BTC价格: ${btcPrice}');
      } else {
        print('首页数据加载失败: ${response.message}');
      }
    } catch (e) {
      print('获取首页数据异常: $e');
    } finally {
      isLoadingHomeData.value = false;
    }
  }

  /// 启动数据轮询
  void _startPolling() {
    // 如果已经有定时器在运行，先停止它
    _stopPolling();

    // 创建新的定时器，每隔pollingInterval毫秒执行一次
    _pollingTimer =
        Timer.periodic(Duration(milliseconds: pollingInterval), (_) {
      if (isPollingEnabled.value) {
        _pollingFetchHomeData();
      }
    });
  }

  /// 停止数据轮询
  void _stopPolling() {
    _pollingTimer?.cancel();
    _pollingTimer = null;
  }

  /// 暂停或恢复轮询
  void togglePolling(bool enable) {
    isPollingEnabled.value = enable;
    if (enable && _pollingTimer == null) {
      _startPolling();
    }
  }

  /// 轮询获取首页数据（优化版本）
  Future<void> _pollingFetchHomeData() async {
    // 如果已经在加载中，跳过本次轮询
    if (isLoadingHomeData.value) return;

    // 检查是否需要更新数据（根据时间间隔或应用状态）
    final now = DateTime.now();
    final timeSinceLastChange = now.difference(_lastDataChangeTime).inSeconds;

    // 如果数据在30秒内有更新，则降低轮询频率（每5分钟一次）
    if (timeSinceLastChange < 30 && timeSinceLastChange % 300 != 0) {
      return;
    }

    try {
      isLoadingHomeData.value = true;
      final response = await _homeService.getHomeData();

      if (response.isSuccess && response.data != null) {
        // 计算数据哈希值，用于比较数据是否有变化
        final newDataHash = response.data.toString().hashCode.toString();

        // 只有当数据有变化时才更新UI
        if (newDataHash != _lastDataHash) {
          homeData.value = response.data!;
          _lastDataHash = newDataHash;
          _lastDataChangeTime = now;
          _unchangedDataCount = 0; // 重置无变化计数器
        } else {
          // 数据无变化，增加计数器
          _unchangedDataCount++;
        }
      }
    } catch (e) {
      // 出错时不更新UI，但记录错误
      print('轮询获取首页数据异常: $e');
    } finally {
      isLoadingHomeData.value = false;
    }
  }

  /// 获取我的合约列表

  /// 获取格式化的BTC余额显示（完全安全）
  String getFormattedBtcBalance() {
    if (!hasBtcInfo) return '-- BTC';
    final balance = userContractData.value?.btcNumValue ?? 0.0;
    if (balance == 0) return '0.000000000 BTC';
    return '${balance.toStringAsFixed(9)} BTC';
  }

  /// 获取格式化的USD价值显示（完全安全）
  String getFormattedUsdValue() {
    if (!hasBtcInfo) return '--';
    final value = btcTotalValue;
    if (value < 0.01) return '\$0.00';
    return '\$${value.toStringAsFixed(2)}';
  }

  /// 获取合约剩余时间显示（完全安全）
  String getContractRemainingTime(UserContract contract) {
    if (contract.remaining == null) return '--';

    final hours = contract.remainingHours;
    if (hours < 1) {
      return '${contract.remainingSeconds}秒';
    } else if (hours < 24) {
      return '${hours.toStringAsFixed(1)}小时';
    } else {
      return '${contract.remainingDays.toStringAsFixed(1)}天';
    }
  }

  /// 获取合约标题（安全）
  String getContractTitle(UserContract contract) {
    return contract.safeTitle;
  }

  /// 获取合约描述（安全）
  String getContractDescribe(UserContract contract) {
    return contract.safeDescribe;
  }

  /// 获取合约算力显示（安全）
  num? getContractComputingPower(UserContract contract) {
    return contract.computingPower;
  }

  /// 检查数据完整性
  bool get hasValidData => userContractData.value != null;

  /// 获取数据状态描述
  String getDataStatusDescription() {
    if (!hasValidData) return 'no_records'.tr;
    if (!hasContracts) return 'no_records'.tr;
    return 'success'.tr;
  }

  /// 刷新所有数据
  Future<void> refreshAllData() async {
    try {
      isRefreshing.value = true;
      await loadInitialData();
    } finally {
      isRefreshing.value = false;
    }
  }

  /// 创建广告合约
  Future<void> createAdsContract(Map<String, dynamic> params) async {
    try {
      final response = await _homeService.createAdsContract(params);

      if (response.isSuccess) {
        // Get.snackbar(
        //   'success'.tr,
        //   'ad_contract_created_success'.tr,
        //   backgroundColor: Color(0xFF4ECDC4),
        //   colorText: Colors.white,
        //   snackPosition: SnackPosition.TOP,
        //   margin: EdgeInsets.all(16),
        //   borderRadius: 12,
        // );
      } else {
        // _showErrorMessage('ad_contract_create_failed'.tr, response.message);
      }
    } catch (e) {
      // print('创建广告合约异常: $e');
      // _showErrorMessage('ad_contract_create_failed'.tr, e.toString());
    }
  }

  /// 显示错误消息
  void _showErrorMessage(String title, String? message) {
    // Get.snackbar(
    //   title,
    //   message ?? 'unknown_error'.tr,
    //   backgroundColor: Colors.red,
    //   colorText: Colors.white,
    //   snackPosition: SnackPosition.TOP,
    //   margin: EdgeInsets.all(16),
    //   borderRadius: 12,
    // );
  }

  /// 获取合约状态颜色
  Color getStatusColor(int status) {
    switch (status) {
      case 1:
        return Colors.green;
      case 0:
        return Colors.red;

      default:
        return Colors.orange; // 默认状态颜色
    }
  }

  /// 获取合约状态文本
  String getStatusText(int status) {
    switch (status) {
      case 1:
        return 'running'.tr;
      case 0:
        return 'stopped'.tr;
      default:
        return 'unknown'.tr;
    }
  }
}
